//=======企业采购目录===============


// 页面进入初始化事件
function myPageInit() {

    // ----写到全局导航里了
    // 采购清单购物车总数
    // let url = "/api/launcher/ordercenter/application/invoke?action=/ShoppingCartService/getCartCount";
    // axiosService(url, {}).then( res=>{
    // 	console.log(res);

    // 	if(res.success){
    // 		h3ui.widgets.Buttons161.props.name = '采购清单('.concat(res.data).concat(')');
    // 	}

    // })


}

//变量 标识 Purchase catalogue标签
var selectRowListIdName='';


//企业采购目录表id
var expireFormList='FormList15';


//打开购物车页面  --- 写到全局导航里了
function toCartPage() {

    var pageCode = "cart_list";
    var param = {};

    let hash = '/api/launcher/ordercenter/app_runtime/index.html#/home/ordercenter?pageCode=' + pageCode;
    window.open(window.location.origin + hash, '_self');

    // toModePage(pageCode,param);
}


// 加入采购单
function joinOrder(evt) {
    debugger
}

// 切换展现形式
function btnClick() {
    // 获取包裹列表组件的栅格
    let Grid16 = h3ui.widgets.Grid16.props;
    // 获取包裹卡片组件的栅格
    let Grid17 = h3ui.widgets.Grid17.props;
    if (Grid16.visible.display) {
        Grid16.visible.display = '';
        Grid17.visible.display = 'none';
    } else {
        Grid16.visible.display = 'none';
        Grid17.visible.display = '';
    }
}


//单元项渲染事件

function rowColor(evt) {

    let {components, col, row, formatText} = evt.data;

    if (row.expire) {

        if (col.key == 'inquiry_id') {
            components[0].props.fontColor = '#1890ff';
        } else {
            var s1 = new Date(row.expire).getTime();
            var s2 = new Date().getTime();
            var s3 = (s1 - s2) / 86400000;

            if (s3 < 60) {
                components[0].props.fontColor = '#ff0000';
            }
        }
    }
    //渲染加入列表染色
    if (col.key==='exends_attr'){
        if (row.count==row.min_order)
        components[0] = { type: 'Tag', props: {
                text: formatText,
                color: '#ff0000'
            }
        };

        if (row.count>row.min_order){
            components[0] = { type: 'Tag', props: {
                    text: formatText,
                    color: '#FFD700'
                }
            };
        };
    }


}


/**
 * 企业采购目录
 */
function toLoadQycgmlList(evt) {
    console.log(12323);

    zloadList(evt, "purchaseLoop");
}


/**
 * 询价定标商品
 */
function toLoadSingleList(evt) {
    console.log(12323);

    zloadList(evt, "purchaseSingleList");
}


/**
 *  历史询价定标商品
 */
function toLoadHistoryList(evt) {

    zloadList(evt, "purchaseSingleExpireList");
}


/**
 * vmi
 */
function toLoadVMiList(evt) {
    console.log(12323);

    zloadList(evt, "purchaseVmiList");
}

//============开启采购目录加入采购清单数量编辑权限=================//
//自动打开行编辑权限
function codingText(evt){
    if (evt==='FormList12'){
        return;
    }
    h3ui.widgets[evt].props.editing = false;  //列表id
    // 关闭行编辑权限
    h3ui.widgets[evt].props.dataSource.rowsStatus = {};
    h3ui.widgets[evt].props.dataSource.colsStatus = {};
    // 特定字段可编辑 c8kzq6ph39gw为模型对应的字段编码
    let colKey = 'count';   //需要打开的字段编码
    //添加数组字段
    let cols=["count","customer_sku"]
    // 获取模型字段列表
    h3ui.widgets[evt].props.editing = true;
    let properties = h3ui.models.t_goods_purchase.schema.properties;   //修改字段编码t_goods_purchase
    for(let propertie of properties){
        // 开启当前列数据权限
        h3ui.widgets[evt].props.dataSource.colsStatus = Object.assign(h3ui.widgets[evt].props.dataSource.colsStatus, {
            [propertie.code]: {
                writable:cols.includes(propertie.code)
            }
        })
    }
}

//=========通过询价单id点击跳转到询价单详情页面 =========


function toLinkInquiryDetail(evt) {

    // 获取单击的列
    let col = evt.data.col;
    // 获取行信息
    let row = evt.data.row;
    var val = row[col.key];

    var appCode = "sourcingcenter";
    var pageCode = "inquiry_detail";
    var param = {
        clickcloumn: val,
        link: "purchasing_list"
    };

    toModePage(pageCode, param, appCode);
}

//=============================


//=============行点击事件配置=======

// 行单击事件
function formListRowClick(evt) {
    console.log(evt);

    // 获取单击的列
    let col = evt.data.col;
    // 编辑的列字段
    let editField = ['customer_sku'];
    // 点击跳转的字段
    let jumpLinkField = ['inquiry_id'];

    if (jumpLinkField.includes(col.key)) {
        //击跳转到询价单详情页面
        toLinkInquiryDetail(evt);

    }
    //全部打开不需要点击事件
    /*else if(editField.includes(col.key)){
        //去编辑操作
        toOpenEditStatus(evt);
    }
    */
}

//===========^^^^^^行点击事件配置===========================


//===========  客户sku 编辑 ==============

// 开启表单可编辑
function toOpenEditStatus(evt) {

    // 获取单击的列
    let col = evt.data.col;
    // 获取行信息
    let row = evt.data.row;
    // 关闭列表编辑权限
    h3ui.widgets[evt.node.id].props.editing = false;
    // 关闭行编辑权限
    h3ui.widgets[evt.node.id].props.dataSource.rowsStatus = {}
    // 获取列表信息
    let items = h3ui.widgets[evt.node.id].props.dataSource.items;

    // 特定字段可编辑 c8kzq6ph39gw为模型对应的字段编码
    let schemaCode = evt.node.props.bindingModel.schemaCode;

    // 开启表单可编辑
    openEditStatus(evt.node.id, items, row, col.key, schemaCode);

}


// 触发失焦事件
function triggerUpdata(evt) {
    let schemaCode = evt.node.props.bindingModel.schemaCode;
    console.log(evt);
    var key = evt.data.col.key;
    if (key==="count"){
        return;
    }
    var param = {[key]: evt.data.row[key]};
    h3ui.models[schemaCode].schema.properties.filter(a => a.isSystemProperty).forEach(a => param[a.code] = evt.data.row[a.code]);

    // upadateInfo( param, evt.node.id, schemaCode);

    let formListId=evt.node.id;
    h3ui.services.midfyCustSku({id: param.id, customer_sku: param.customer_sku}).then(res => {
        if (res.success) {
            // 关闭表单的编辑状态
            h3ui.widgets[evt.node.id].props.editing = false;
            reloadList(formListId);
            myPageInit();
        } else {
            h3ui.$message.error('调用接口出错')
        }
    })

}

/**
 * 开启对应行中的列编辑状态
 * id 表单对应的id值
 * items 表单数据
 * row 当前点击的行信息
 * colKey 当前点击的列key 其值对应为模型中的字段编码
 **/
function openEditStatus(id, items, row, colKey, schemaCode) {
    // 开启列表的编辑权限
    h3ui.widgets[id].props.editing = true;
    // 获取模型字段列表
    let properties = h3ui.models[schemaCode].schema.properties;
    for (let propertie of properties) {
        // 开启当前列数据权限
        h3ui.widgets[id].props.dataSource.colsStatus = Object.assign(h3ui.widgets[id].props.dataSource.colsStatus || {}, {
            [propertie.code]: {
                writable: propertie.code === colKey
            }
        })
    }
    for (let item of items) {
        // 开启当前行的列权限
        h3ui.widgets[id].props.dataSource.rowsStatus = Object.assign(h3ui.widgets[id].props.dataSource.rowsStatus || {}, {
            [item.id]: {
                [colKey]: {
                    writable: item.id === row.id
                }
            }
        })
    }
}

/**
 * row 行数据
 * id 当前列表组件id
 * schemaCode 当前中心模型的模型编码
 * 更新数据信息
 **/
function upadateInfo(row, id, schemaCode) {
    h3ui.models[schemaCode].updateBO({
        schemaCode,
        data: row,
        bizObjectId: row.id
    }).then(res => {
        if (res.data) {
            // 关闭表单的编辑状态
            h3ui.widgets[id].props.editing = false;
        } else {
            h3ui.$message.error('调用接口出错')
        }
    })

}


////===========================

//列表列点击事件
function listAction(evt) {

    var inputNum = "InputNum";

    console.log(evt);
    if (evt.data.action == "加入订单") {
        if (evt.data.row.quote_total_strategy == 1) {
            toCreateOrder(evt);
        } else {
            toCrateCartNotModel(evt)
          //  openModifyNumModal(evt);
        }
    }
}


/**
 * 跳转到生成订单页面
 */
function toCreateOrder(evt) {

    var inquiryId = evt.data.row.inquiry_id;

    h3ui.services.findIds({inquiryId}).then(res => {

        if (res.success) {
            h3ui.$confirm({
                title: '由于该商品属于整单询价,需要提交商品为序号为:[' + res.data + '],是否加入?',
                onOk() {
                    joinWholeOrder(inquiryId);
                }
            });

        } else {
            h3ui.$message.error(res.errMessage || '提交失败');
        }
    })

}
// 整单加入
function joinWholeOrder(inquiryId) {
    h3ui.services.joinWholeOrder({inquiryId}).then(res => {
        if (res.success) {

            var pageCode = "toOrder";

            var ids = res.data;
            if (ids instanceof Array) {
                ids = res.data.join();
            }
            var mode = 'detail';

            h3ui.openPage('innerLink', pageCode, 'self', {ids, mode});


        } else {
            h3ui.$message.error(res.errMessage || '提交失败');
        }
    })

}


//打开修改数量对话框
function openModifyNumModal(evt) {

    var modalId = "Modal7";
    var inputNum = "InputNum";
    var reloadListId = "FormList15";

    //修改数量
    h3ui.widgets[inputNum].props.value = evt.data.row.num;
    h3ui.widgets[inputNum].props.rowId = evt.data.row.id;


    if (evt.data.row.type == 2) {
        reloadListId = "FormList15";
        //打开对话框
        h3ui.widgets[modalId].props.visible = true;
    } else {
        reloadListId = "FormList17";
        if (evt.data.row.maximum && evt.data.row.maximum > evt.data.row.num) { // 库存大于询包数量才弹框选择数量
            //打开对话框
            h3ui.widgets[modalId].props.visible = true;
        } else {
            toCrateCart({node: {id: null}});
        }

    }
    h3ui.widgets[inputNum].props.reloadListId = reloadListId;


}


//生成采购清单
function toCrateCart(evt) {
    var inputNum = "InputNum";
    var closeModalId = evt.node.id;
    var serviceName = "toCrateCart";
    var num = h3ui.widgets[inputNum].props.value.toString();

    var purchaseId = h3ui.widgets[inputNum].props.rowId;
    var reloadListId = h3ui.widgets[inputNum].props.reloadListId;

    var param = {purchaseId, num};
    var map = {serviceName, param, reloadListId, closeModalId};

    let url = "/api/launcher/ordercenter/application/invoke?action=/ShoppingCartService/toCrateCart";
    axiosService(url, map.param).then(res => {
        if (res.success) {
            h3ui.$message.success('提交成功');

            if (map.reloadListId) {
                reloadList(map.reloadListId);
            }

            if (map.closeModalId) {
                map.closeModalId.split(",").forEach(a => {
                    if (a) h3ui.widgets[a].props.visible = false;
                })
            }

            myPageInit();

        } else {

            if (res.errCode == "-2") {
                if (map.closeModalId) {
                    map.closeModalId.split(",").forEach(a => {
                        if (a) h3ui.widgets[a].props.visible = false;
                    })
                }
            }
        }
    })
    /**h3ui.services[map.serviceName](map.param).then(res=>{
        if(res.success ){
            h3ui.$message.success('提交成功');

            if(map.reloadListId){
                reloadList(map.reloadListId);
            }

            if(map.closeModalId){
                map.closeModalId.split(",").forEach(a=>{
                    if(a) h3ui.widgets[a].props.visible= false;
                })
            }

			myPageInit();

        } else {

			if(res.errCode=="-2"){
				if(map.closeModalId){
					map.closeModalId.split(",").forEach(a=>{
						if(a) h3ui.widgets[a].props.visible= false;
					})
				}
			}
        }
    })*/

}




//无弹框生成采购清单
function toCrateCartNotModel(evt) {

    var reloadListId = evt.node.id;

    let num = evt.data.count;

    let purchaseId = evt.data.id;

    var param = {purchaseId, num};

    let url = "/api/launcher/ordercenter/application/invoke?action=/ShoppingCartService/toCrateCart";
    axiosService(url, param).then(res => {
        if (res.success) {
            h3ui.$message.info("加入成功");
        }
        else {
            h3ui.$message.error(res.errMessage);
        }
    })
}

/**
 * 企业采购目录批量加入采购清单
 */
function loopBatchAddCart(evt){
    debugger;
    var reloadListId= "FormList15";
    var rows = h3ui.widgets[reloadListId].props.selectedRow;
    if(rows.length==0){
        h3ui.$message.info("请勾选数据");
        return;
    }
    let purchaseDtoList=[];
    let quoteStrategy = ''
    rows.forEach(a=>{
        let quoteStrategys='';
        if (a.quote_total_strategy===1){
            quoteStrategy += quoteStrategys.concat(a.id).concat(',');
        } else {
            let purchaseDto={
                purchaseId:a.id,
                num:a.count
            };
            purchaseDtoList.push(purchaseDto);
        }
    });

    if (quoteStrategy!=''){
        h3ui.$message.info("选择数据中序号为:"+quoteStrategy.substr(0,quoteStrategy.length-1)+"是整单购买商品，不能加入采购清单！");
        return;
    }

    let param={
        purchaseDtoList:purchaseDtoList
    };
    var purchaseIds= h3ui.widgets[reloadListId].props.selectedRowKeys;
    let url = "/api/launcher/ordercenter/application/invoke?action=/ShoppingCartService/batchAddCart";

    axiosService(url,param).then(res => {
        if (res.success) {
            reloadList(reloadListId);
            myPageInit();
            h3ui.$message.info("加入成功");
        }else {
            h3ui.$message.error(res.errMessage);
        }
    })

}

/**
 * 询价定标批量加入购物车
 * @param {*} evt
 */
function batchAddCart(evt) {

    var reloadListId = "FormList17";
    var rows = h3ui.widgets[reloadListId].props.selectedRow;

    if (rows.length == 0) {
        h3ui.$message.info("请勾选数据");
        return;
    }
    var temp = rows.filter(a => a.quote_total_strategy == 1).map(a => a.id);
    if (temp.length > 0) {
        h3ui.$message.info("选择数据中序号为：" + temp.join() + "是整单购买商品，不能加入采购清单！");
        return;
    }

    var purchaseIds = h3ui.widgets[reloadListId].props.selectedRowKeys;

    let url = "/api/launcher/ordercenter/application/invoke?action=/ShoppingCartService/batchAddCart";
    axiosService(url, {purchaseIds}).then(res => {
        if (res.success) {
            reloadList(reloadListId);
            myPageInit();
        }else {
           h3ui.$message.error(res.errMessage);
        }
    })

    /**h3ui.services.batchAddCart({purchaseIds}).then(res=>{
		if(res.success){
			reloadList(reloadListId);
			myPageInit();
		}
	})*/


}


/**
 * 创建发货通知单
 */
function toDeliverNotice(evt) {

    var selectListId = "FormList18";

    var selectedRowKeys = h3ui.widgets[selectListId].props.selectedRowKeys;

    if (selectedRowKeys.length == 0) {
        h3ui.$message.error("请选择一行");
        return false;
    }
    var pageCode = "deliverNotice";


    var mode = "create";
    var ids = selectedRowKeys.join();

    var param = {mode, ids};

    toModePage(pageCode, param);


}


/**
 * 发起未税金额流程
 */
function updatePretaxPrice(evt) {

    var selectListId = "FormList15";

    var selectedRowKeys = h3ui.widgets[selectListId].props.selectedRowKeys;

    if (selectedRowKeys.length != 1) {
        h3ui.$message.error("请选择一行");
        return false;
    }
    var pageCode = "goodsPpriceFlow";

    // 跳转发起定标商品调价流程
    var mode = "create";
    var purchaseId = selectedRowKeys[0];
    var workflowCode = "goodsPriceFlow";

    var param = {mode, purchaseId, workflowCode};

    toModePage(pageCode, param);

}


/**
 * 提交修改商品到期时间
 * @param evt
 */
function updateExpire(evt) {

    var service = "midfyExpire";
    var selectListId = expireFormList;
    var expire = h3ui.widgets["expireDatePicker"].props.value;

    toCallService({
        formListId: selectListId,
        reloadListId: selectListId,
        serviceName: service,
        msg: "",
        closeModalId: evt.node.id,
        param: {expire},
    });
}

/**
 *
 * 打开企业采购 到期时间对话框
 */
function openExpireModal(evt) {
    console.log("openExpireModal");
    // expireDatePicker
    var selectRowListId = "FormList15";

    let buttonId = evt.node.id;
    if (buttonId==='Buttons186_Modal5'){
        selectRowListId='FormList17';
    }
    expireFormList=selectRowListId;

    var selectedRow = h3ui.widgets[selectRowListId].props.selectedRow;
    let length = selectedRow.length;
    if (length == 0) {
        h3ui.$message.error("请选择一行");
        return false;
    }
    if (length == 1) {
        h3ui.widgets["expireDatePicker"].props.value = selectedRow[0].expire;
    }

    openModal(evt);

}


/**
 *
 * 打开采购目录(多次购买)成本中心对话框
 */
function openMultipleCostCenterModal() {
    console.log("打开采购目录(多次购买)成本中心对话框");
    openCostCenterMOdal("FormList15");
}

/**
 * 打开询价定标(单次购买) 成本中心对话框
 */
function openSignleCostCenterModal(et) {
    console.log("打开询价定标(单次购买) 成本中心对话框");
    openCostCenterMOdal("FormList17");

}

/**
 * 打开修改成本中心对话框
 */
function openCostCenterMOdal(listId) {

    var selectedRow = h3ui.widgets[listId].props.selectedRow;
    let length = selectedRow.length;


    if (length != 1) {
        h3ui.$message.error("请选择一行");
        return false;
    }

    var data = selectedRow[0];
    if (length == 1) {
        h3ui.models.t_goods_purchase.newItem();
        h3ui.models.t_goods_purchase.item.cost_center_id = [{id: data.cost_center_id, name: data.cost_center_name}];
        h3ui.models.t_goods_purchase.item.type = data.type;
        h3ui.models.t_goods_purchase.item.id = data.id;
        h3ui.widgets.Modal4.props.visible = true;
        h3ui.widgets.Modal4.props.reloadListId = listId;
    } else {
        h3ui.$message.error("数据错误");
        return false;
    }

}

/**
 * 提交修改商品成本中心
 * @param evt
 */
function updateCostCenter() {

    var {id, type, cost_center_id} = h3ui.models.t_goods_purchase.item;

    if (cost_center_id == null || cost_center_id.length == 0
        || cost_center_id[0].id == null || cost_center_id[0].name == null) {
        h3ui.$message.error("请选择成本中心");
        console.log("cost_center_id");
        return false;
    }

    var cost_center_name = cost_center_id[0].name;
    var cost_center_id = cost_center_id[0].id;

    var param = {
        data: {id, cost_center_name, cost_center_id}
    }

    var closeModalId = "Modal4";
    var reloadListId = h3ui.widgets[closeModalId].props.reloadListId;
    var serviceName = "midfyCostCenterName";

    callService({
        serviceName,
        param,
        reloadListId,
        closeModalId
    });


}


/**
 * 提交修改商品
 * @param evt
 */
function updateAdjustGoods(evt) {
    var service = "adjustGoods";
    ;
    var multiplePurchases = h3ui.widgets["minOrderInput"].props.multiplePurchases;
    var selectListId = "FormList15";
    if (!multiplePurchases) {
        selectListId = "FormList17";
    }

    if (selectRowListIdName !=''){
        selectListId = "FormList20";
    }

    var maximum = h3ui.widgets["maximumInput"].props.value.toString() || 0;
    var minOrder = h3ui.widgets["minOrderInput"].props.value.toString() || 0;

    toCallService({
        formListId: selectListId,
        reloadList: selectListId,
        reloadListId:selectListId,
        serviceName: service,
        msg: "",
        closeModalId: evt.node.id,
        param: {minOrder, maximum},
    });


}

/**
 *
 * 打开企业采购 调整商品对话框
 */
function openMultipleGoodsModal(evt) {

    //瓦克采购标签标识,每次置为空
    selectRowListIdName='';
    var selectRowListId = "FormList15";

    if (evt.data.name==='Modify'){
        selectRowListId='FormList20';
        selectRowListIdName='FormList20';
    }

    h3ui.widgets["minOrderInput"].props.multiplePurchases = true;

    var selectedRow = h3ui.widgets[selectRowListId].props.selectedRow;
    let length = selectedRow.length;
    if (length == 0) {
        h3ui.$message.error("请选择一行");
        return false;
    }
    if (length == 1) {
        h3ui.widgets["minOrderInput"].props.value = selectedRow[0].min_order;
    }

    openModal(evt);

}

/**
 * 打开询价定标 调整商品对话框
 */
function openSignleGoodsModal(evt) {

    var selectRowListId = "FormList17";

    h3ui.widgets["minOrderInput"].props.multiplePurchases = false;

    var selectedRow = h3ui.widgets[selectRowListId].props.selectedRow;
    let length = selectedRow.length;
    if (length != 1 || length == 0) {
        h3ui.$message.error("只能选择一行数据");
        return false;
    }

    h3ui.widgets["minOrderInput"].props.value = selectedRow[0].min_order;

    openModal(evt);

}


// 商品比例调整
function updateAdjustRatio(evt) {

    var selectListId = 'FormList12';
    var reloadListId = selectListId;

    var adjustRatio = h3ui.widgets.InputNumber198.props.value.toString() || 0;

    toCallService({
        formListId: selectListId,
        reloadListId: reloadListId,
        serviceName: "updatePlatformAdjustRatio",
        msg: "",
        closeModalId: evt.node.id,
        param: {adjustRatio},
    });
}


/**
 * 打开对话框,按钮的id 设置为 xxx_Modalx 如: Buttons_Modal1
 */
function openModal(evt) {
    debugger;
    var modalId = evt.node.id.split("_")[1];
    h3ui.widgets[modalId].props.visible = true;
}

/**
 * 关闭对话框
 */
function closeModal(evt) {
    var modalId = evt.node.id.split("_")[1];
    h3ui.widgets[modalId].props.visible = false;
}

// ============公共方法=======


//触发列表刷新事件
function reloadList(fromListId) {
    doReloadList({pageIndex: 1, node: {id: fromListId}});
}
//标签页切换 刷新列表, 要求 标签页id 是 "xxx"+"_"+listid
function tabLoadList(evt) {
    doReloadList({node: {id: evt.data.activeKey.split("_")[1]}});
}

//列表刷新
function doReloadList(evt) {
    var list = h3ui.widgets[evt.node.id];

    var queryId = list.childIds.find(a => a.includes("ModelQueryForm"));

    var filter = h3ui.widgets[queryId].props.value || {};

    filter = JSON.parse(JSON.stringify(filter));

    var pageId = list.childIds.find(a => a.includes("Pagination"));

    var pageIndex = h3ui.widgets[pageId].props.current;
    var pageSize = h3ui.widgets[pageId].props.pageSize;


    list.emit("load", {pageIndex, pageSize, filter});


    list.props.selectedRowKeys = [];
    list.props.selectedRow = [];

}

/**
 * 前台自定义服务
 */
function zloadList(evt, serviceName) {
    var list = h3ui.widgets[evt.node.id];

    var queryId = list.childIds.find(a => a.includes("ModelQueryForm"));

    var filter = h3ui.widgets[queryId].props.value || {};

    filter = JSON.parse(JSON.stringify(filter));

    var pageId = list.childIds.find(a => a.includes("Pagination"));

    var pageIndex = h3ui.widgets[pageId].props.current;
    var pageSize = h3ui.widgets[pageId].props.pageSize;



    if (serviceName) {
        Object.assign(filter, {pageIndex, pageSize});

        h3ui.services[serviceName](filter).then(res => {
            list.props.dataSource = {
                items: res.data.data,
                total: res.data.total
            }
            codingText(list.id);
        })
    } else {
        var schemaCode = list.props.bindingModel.schemaCode;
        h3ui.models[schemaCode].listBO({pageIndex, pageSize, filter}).then(res => {

            list.props.dataSource = res;
            codingText(list.id);
        })
    }

}


/**
 * 企业商城加载事件
 * @param evt
 */
function  customLoadList(evt){
    let {pageIndex, pageSize, filter} = evt.data;
    let listId = evt.node.id;
    let schemaCode = h3ui.widgets[listId].props.bindingModel.schemaCode;
    let dataSource = h3ui.models[schemaCode];
    ilter = JSON.parse(JSON.stringify(filter)) || {};
    let param ={
        id:filter.id,
        brand:filter.brand,
        name:filter.name,
        page:pageIndex,
        limit:pageSize,

    };
    //调用接口api
    let url = "/api/launcher/" + h3ui.appInfo.appCode + "/application/invoke?action=/MallService/selectMallGoods";
    axiosService(url,param).then(res=>{
        if(res.success){
            console.info(res.data);
            h3ui.widgets[listId].props.dataSource ={
                items: res.data.data,
                total: res.data.total
            }
        }
    });

}

/**
 * 前台自定义服务
 */
function xloadList(evt, call) {
    var list = h3ui.widgets[evt.node.id];

    var queryId = list.childIds.find(a => a.includes("ModelQueryForm"));


    var pageId = list.childIds.find(a => a.includes("Pagination"));

    var pageIndex = h3ui.widgets[pageId].props.current;
    var pageSize = h3ui.widgets[pageId].props.pageSize;


    var filter = h3ui.widgets[queryId].props.value || {};


    if (call != undefined && call instanceof Function) {

        var callFilter = JSON.parse(JSON.stringify(filter || {}));

        call(callFilter);

        filter = callFilter;
    }


    var schemaCode = list.props.bindingModel.schemaCode;

    h3ui.models[schemaCode].listBO({pageIndex, pageSize, filter}).then(res => {

        list.props.dataSource = res;

    })
}


/**
 * 提交自定义业务服务
 * map:{formListId : "", // select列表id
 * 	reloadListId : "",// 重新加载的list
 *  reloadListFunction : "",// 调用自定义list 的加载方法
 * 	serviceName : "",// 服务名称
 * 	msg :"", // 提示内容
 * 	closeModalId:"", // 需要关闭的对话框id, 多个用","隔开
 * 	param : {} // 提交参数
 * }
 */
function toCallService(map) {

    var selectKeys = h3ui.widgets[map.formListId].props.selectedRowKeys;
    let length = selectKeys.length;
    if (length == 0) {
        h3ui.$message.error("请选择一行数据");
        return false;
    }
    map.param.ids = selectKeys;

    h3ui.$confirm({
        title: map.msg + '确认提交吗',
        onOk() {
            callService(map);
        }
    });
}


/** *
 * @param {serviceName,param,reloadListId,closeModalId} map
 *
 * serviceName 服务名称
 * param  服务参数
 * reloadListId 服务成功后指定刷新列表
 * closeModalId 服务成功后指定关闭对话框
 */
function callService(map) {
    h3ui.services[map.serviceName](map.param).then(res => {
        if (res.success) {
            h3ui.$message.success('提交成功');

            if (map.reloadListId) {
                reloadList(map.reloadListId);
            }

            if (map.closeModalId) {
                map.closeModalId.split(",").forEach(a => {
                    if (a) h3ui.widgets[a].props.visible = false;
                })
            }
        } else {
            h3ui.$message.error(res.errMessage || '提交失败');
        }
    })
}


/**
 *  跳转表单页面并url携带参数
 *  pageCode // 页面code *
 *  param    // 参数
 *  appCode  // 应用code
 */
function toModePage(pageCode, param, appCode) {
    // 获取页面url地址
    let url = window.location.href.substring(0, window.location.href.indexOf('?'));

    if (appCode) {
        url = url.replaceAll(h3ui.appInfo.appCode, appCode);
    }

    var paramstr = Object.keys(param).map(a => {
        return "&".concat(a).concat("=").concat(param[a])
    }).join("");

    // 跳转创建页面
    window.location.href = url + '?pageCode=' + pageCode + paramstr;
}


/***
 *  时间格式化
 */
function formatDate(value) {
    let date = new Date(value);
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? ('0' + MM) : MM;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    let h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    let m = date.getMinutes();
    m = m < 10 ? ('0' + m) : m;
    let s = date.getSeconds();
    s = s < 10 ? ('0' + s) : s;
    return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
}


function actionBar(evt) {
    console.log(evt);
    var listId = evt.node.id;
    if (evt.data.code == 'custExport') {
        opentExportSelect(listId);
    }

}


// 打开 导出选项弹框
function opentExportSelect(listId) {
    var keys = h3ui.widgets[listId].props.selectedRowKeys;
    if (keys.length == 0) {
        h3ui.$message.info("请选择至少一条数据");
        return;
    }

    h3ui.widgets.RadioGroup1.props.listId = listId;
    var modalProps = h3ui.widgets.Modal8.props;
    modalProps.visible = true;
    modalProps.confirmLoading = false;
}
//  导出
function postExport() {
    var modalProps = h3ui.widgets.Modal8.props;
    var listId = h3ui.widgets.RadioGroup1.props.listId;
    var ids = h3ui.widgets[listId].props.selectedRowKeys;
    if (ids.length == 0) {
        h3ui.$message.info("请选择至少一条数据");
        modalProps.visible = false;
        return;
    }
    var fileType = h3ui.widgets.RadioGroup1.props.value;
    if (!fileType) {
        h3ui.$message.info("请选择导出类型");
        return;
    }
    modalProps.confirmLoading = true;
    h3ui.services.exportGoodsPurchaseReport({data: {ids, fileType}}).then(res => {
        if (res.success) {
            //调用下载全局弹框
            h3ui.$message.info("导出成功,调用下载全局弹框,等待完善");
            modalProps.visible = false;
            h3ui.widgets[listId].props.selectedRowKeys = [];
            h3ui.widgets[listId].props.selectedRow = [];

            //打开下载弹框列表
            h3ui.widgets.gmNoticeBar1.props.visible = true;

        } else {
            h3ui.$message.error(res.errMessage || "导出失败");
        }
        modalProps.confirmLoading = false;
    })
}

/* ----------------------------跨应用服务调用---------------------------------------------------- */
// 封装了axiosService 方便调用其他应用的服务
const axiosService = function (url, param) {
    return new Promise(function (resolve, reject) {
        h3ui.axios({
            method: 'post',
            url,
            data: param,
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem("token"),
                'Content-Type': 'application/json;charset=UTF-8'
            }
        }).then(function (res) {
            console.log(res);

            if (res.status == 200) {
                resolve(res.data);
            } else {
                reject(res);
            }
        }).catch(function (error) {
            h3ui.$message.error(error);
        });
    })
}
